package org.cll.lagou.study.ssm.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 描述信息:
 * 登录拦截器，未登录跳转到登录页面
 * @author CLL
 * @version 1.0
 * @date 2020/6/23 13:41
 */
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("====== preHandle");
        Object user = request.getSession().getAttribute("user");
        if (null == user) {
            String contextPath = request.getServletContext().getContextPath();
            response.sendRedirect(contextPath);
            return false;
        }
        return true;
    }

    /**
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView 封装了数据和视图，可以对返回的数据或者视图进行修改
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("====== postHandle");
    }

    /**
     *
     * @param request
     * @param response
     * @param handler
     * @param ex    可以进行一场的捕获
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("====== afterCompletion");
    }
}